#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <mutex>
#include "util.hpp"
#include "log.hpp"

struct DocInfo
{
    std::string title;  // 标题
    std::string content;  // 内容
    std::string url;  // 网址
    uint64_t doc_id;  // id，类型给大防止越界
};

struct InvertedElem
{
    uint64_t doc_id;
    std::string word;
    int weight;

    InvertedElem(): weight(0) {}
};
// 倒排拉链
typedef std::vector<InvertedElem> InvertedList;
class Index
{
private:
    std::vector<DocInfo> forward_index;  // 正排索引，数组下标天然是文档id
    // 一个关键字可能在一组InvertedElem对应，关键字和倒排拉链映射关系
    std::unordered_map<std::string, InvertedList> inverted_index;
private:
    Index(){}  // 一定要有函数体，不能delete
    Index(const Index&) = delete;
    Index& operator=(const Index&) = delete;

    static Index *instance;
    static std::mutex mtx;
public:
    ~Index() {}
public:
    static Index* GetInstance()
    {
        if (instance == nullptr)
        {
            mtx.lock();
            if (instance == nullptr)
            {
                instance = new Index();
            }
            
            mtx.unlock();
        }

        return instance;
    }

    // 根据doc_id找到文档内容
    DocInfo* GetForwardIndex(uint64_t doc_id)
    {
        if (doc_id >= forward_index.size())
        {
            std::cerr << "doc_id out range, error!" << std::endl;
            return nullptr;
        }

        return &forward_index[doc_id];
    }
    // 根据关键字，获得倒排拉链
    InvertedList* GetInvertedList(const std::string& word)
    {
        auto iter = inverted_index.find(word);
        if (iter == inverted_index.end())
        {
            std::cerr << word << " have no InvertedList" << std::endl;
            return nullptr;
        }

        return &(iter->second);
    }

    // 根据去标签，格式化的文档，构建正排和倒排索引
    // data/raw_html/raw.txt
    bool BuildIndex(const std::string& input)  // parse处理完的数据交过来
    {
        std::ifstream in(input, std::ios::in | std::ios::binary);
        if (!in.is_open())
        {
            std::cerr << "input" << "open error" << std::endl;
            return false;
        }

        std::string line;
        int count = 0;
        while (std::getline(in, line))
        {
            DocInfo* doc = BuildForwardIndex(line);
            if (doc == nullptr)
            {
                std::cerr << "build" << line << "error" << std::endl;  // for debug
                continue;
            }
            BuildInvertedIndex(*doc);

            count++;
            //std::cout << "当前已建立的索引文档:" << count << std::endl;
            LOG(NORMAL, "当前的已经建立的索引文档: " + std::to_string(count));
        }

        return true;
    }

private:
    DocInfo *BuildForwardIndex(const std::string& line)
    {
        // 解析line，字符串切分
        // line -> 3 string, title content url
        std::vector<std::string> results;
        const std::string sep = "\3";  //?转换
        StringUtil::Split(line, &results, sep);
        if (results.size() != 3)
        {
            return nullptr;
        }
        // 字符串填充DocInfo
        DocInfo doc;
        doc.title = results[0];
        doc.content = results[1];
        doc.url = results[2];
        doc.doc_id = forward_index.size();  // 先保存id，再插入，对应的id就是当前doc在vector的下标

        // 插入到正排索引的vector
        forward_index.push_back(std::move(doc));
        return &forward_index.back();
    }
    bool BuildInvertedIndex(const DocInfo& doc)
    {
        // word -> 倒排拉链
        struct word_cnt
        {
            int title_cnt;
            int content_cnt;

            word_cnt(): title_cnt(0), content_cnt(0) {}
        };     

        std::unordered_map<std::string, word_cnt> word_map;  // 暂存词频映射表  

        // 对标题分词
        std::vector<std::string> title_wrods;
        JiebaUtil::CunString(doc.title, &title_wrods);

        // 对标题词频统计
        for (std::string& s : title_wrods)
        {
            boost::to_lower(s);  // 需要统一转化为小写
            word_map[s].title_cnt++; // 如果在就获取，不在新建
        }

        // 对标题分词
        std::vector<std::string> content_wrods;
        JiebaUtil::CunString(doc.content, &content_wrods);

        // 对内容词频统计
        for (std::string& s : content_wrods)
        {
            boost::to_lower(s);  // 需要统一转化为小写
            word_map[s].content_cnt++;  // 如果在就获取，不在新建
        }
#define X 10
#define Y 1
            for (auto& word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = X * word_pair.second.title_cnt + Y * word_pair.second.content_cnt;  // 相关性
                InvertedList &inverted_list = inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }
    }
};

Index *Index::instance = nullptr;
std::mutex Index::mtx;